<template>
    <div
        :class="{ fullscreen: fullscreen }"
        class="tinymce-container"
        :style="{ width: containerWidth }"
    >
        <textarea :id="tinymceId" class="tinymce-textarea" />
        <span v-if="wordCountMax" class="wordcount">{{
            `已输入${wordCount}/${wordCountMax}`
        }}</span>
    </div>
</template>

<script>
import plugins from './plugins'
import toolbar from './toolbar'
import load from './dynamicLoadScript'
// why use this cdn, detail see https://github.com/PanJiaChen/tinymce-all-in-one
// const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce-all-in-one@4.9.5/tinymce.min.js'
// 官方cdn 因为目前没有官方的语言包cdn，下面init时，language_url使用的是PanJiaChen发布的中文语言包
const tinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce@5.6.2/tinymce.min.js'

export default {
    name: 'Tinymce',
    props: {
        id: {
            type: String,
            default: function() {
                return 'vue-tinymce-' + +new Date() + ((Math.random() * 1000).toFixed(0) + '')
            }
        },
        value: {
            type: String,
            default: ''
        },
        wordCountMax: {
            type: [Number, String],
            default: ''
        },
        showMessage: {
            type: Boolean,
            default: true
        },
        plugins: {
            type: Array,
            required: false,
            default() {
                return []
            }
        },
        toolbar: {
            type: Array,
            required: false,
            default() {
                return []
            }
        },
        menubar: {
            type: String,
            default: 'file edit insert view format table'
        },
        height: {
            type: [Number, String],
            required: false,
            default: 360
        },
        width: {
            type: [Number, String],
            required: false,
            default: 'auto'
        }
    },
    data() {
        return {
            hasChange: false,
            hasInit: false,
            tinymceId: this.id,
            fullscreen: false,
            wordCount: 0,
            languageTypeList: {
                'en': 'en',
                'zh': 'zh_CN',
                'es': 'es_MX',
                'ja': 'ja'
            }
        }
    },
    computed: {
        containerWidth() {
            const width = this.width
            if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
                return `${width}px`
            }
            return width
        }
    },
    watch: {
        value(val) {
            if (!this.hasChange && this.hasInit) {
                this.$nextTick(() =>
                    window.tinymce.get(this.tinymceId).setContent(val || ''))
            }
        }
    },
    mounted() {
        this.init()
    },
    activated() {
        if (window.tinymce) {
            this.initTinymce()
        }
    },
    deactivated() {
        this.destroyTinymce()
    },
    destroyed() {
        this.destroyTinymce()
    },
    methods: {
        init() {
            // dynamic load tinymce from cdn
            load(tinymceCDN, (err) => {
                if (err) {
                    this.$message.error(err.message)
                    return
                }
                this.initTinymce()
            })
        },
        initTinymce() {
            const _this = this
            window.tinymce.init({
                selector: `#${this.tinymceId}`,
                language: this.languageTypeList['zh'],
                language_url: 'https://cdn.jsdelivr.net/npm/tinymce-lang/langs/zh_CN.js',
                height: this.height,
                body_class: 'panel-body',
                // object_resizing: false, //关闭表格和图像的内联大小调整控件，关闭后会导致表格的table_resize_bars默认开启失效，无法拖动表格内部的横线竖线来调整行列大小
                branding: false,
                toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
                menubar: this.menubar,
                plugins: this.plugins.length > 0 ? this.plugins : plugins,
                end_container_on_empty_block: true,
                powerpaste_word_import: 'clean',
                code_dialog_height: 450,
                code_dialog_width: 1000,
                advlist_bullet_styles: 'square',
                advlist_number_styles: 'default',
                imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
                default_link_target: '_blank',
                link_title: false,
                nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
                init_instance_callback: editor => {
                    const emitWordCount = (editor) => {
                        const tinylen = editor.getContent().replace(/(<([^>]+)>)/ig, '').replace(/&nbsp;/ig, ' ').length
                        this.wordCount = tinylen
                        this.$emit('get-word-count', this.wordCount)
                        // 如果不用显示提醒框
                        if (!this.showMessage) { return }
                        // 如果输入内容超出最大限制，且页面没有提醒框，则弹出提醒
                        if (this.wordCount > this.wordCountMax && document.getElementsByClassName('el-message').length === 0) {
                            this.$message.warning(`文本内容已超出最大字符${this.wordCountMax}限制！`)
                        }
                    }
                    if (_this.value) {
                        editor.setContent(_this.value)
                        this.wordCountMax && emitWordCount(editor)
                    }
                    _this.hasInit = true

                    // _this.wordCountMax && _this.creatHtmlCount()
                    editor.on('NodeChange Change KeyUp SetContent', () => {
                        this.hasChange = true
                        this.$emit('input', editor.getContent())
                        // 如果有限制字符数，获取当前字符数
                        this.wordCountMax && emitWordCount(editor)
                    })
                },
                setup(editor) {
                    editor.on('FullscreenStateChanged', (e) => {
                        _this.fullscreen = e.state
                    })
                },
                // 自定义上传逻辑
                images_upload_handler: (blobInfo, succFun, failFun) => {
                    const file = blobInfo.blob()
                    this.$api.upload(file).then(res => {
                        succFun(res)
                    }).catch((err) => {
                        console.log(err)
                        failFun('上传失败，请稍后再试')
                    })
                }
            })
        },
        destroyTinymce() {
            const tinymce = window.tinymce.get(this.tinymceId)
            if (this.fullscreen) {
                tinymce.execCommand('mceFullScreen')
            }

            if (tinymce) {
                tinymce.destroy()
            }
        },
        setContent(value) {
            window.tinymce.get(this.tinymceId).setContent(value)
        },
        getContent() {
            window.tinymce.get(this.tinymceId).getContent()
        },
        imageSuccessCBK(arr) {
            const _this = this
            arr.forEach(v => {
                window.tinymce.get(_this.tinymceId).insertContent(`<img class="wscnph" src="${v.url}" >`)
            })
        }
    }
}
</script>

<style scoped>
.tinymce-container {
    position: relative;
    line-height: normal;
}
.tinymce-container >>> .mce-fullscreen {
    z-index: 10000;
}
.tinymce-textarea {
    visibility: hidden;
    z-index: -1;
}
.editor-custom-btn-container {
    position: absolute;
    right: 4px;
    top: 4px;
    /*z-index: 2005;*/
}
.fullscreen .editor-custom-btn-container {
    z-index: 10000;
    position: fixed;
}
.editor-upload-btn {
    display: inline-block;
}
.wordcount {
    position: absolute;
    right: 16px;
    bottom: 0;
    padding: 1px 0;
    vertical-align: top;
    font-size: 12px;
}
.panel-body p {
    margin: 0;
}
</style>
